package com.cz.ssyx.common.auth;

import com.cz.ssyx.common.constant.RedisConst;
import com.cz.ssyx.common.utils.JwtHelper;
import com.cz.ssyx.vo.user.UserLoginVo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @descriptions:
 * @author: Joker.
 * @date: 2024/4/24 18:41
 * @version: 1.0
 */

public class UserLoginInterceptor implements HandlerInterceptor {

    private RedisTemplate redisTemplate;

    public UserLoginInterceptor(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        this.getUserLoginVo(request);
        return true;
    }

    private void getUserLoginVo(HttpServletRequest request) {
        //从请求头中获取token
        String token = request.getHeader("token");

        //如果不为空
        if (token != null) {
            Long userId = JwtHelper.getUserId(token);
            //根据userId从redis获取用户信息
            UserLoginVo userLoginVo = (UserLoginVo) redisTemplate.opsForValue()
                    .get(RedisConst.USER_LOGIN_KEY_PREFIX + userId);
            //将数据放到线程中
            AuthContextHolder.setUserId(userLoginVo.getUserId());
            AuthContextHolder.setUserLoginVo(userLoginVo);
            AuthContextHolder.setWareId(userLoginVo.getWareId());
        }
    }
}
